import {url} from '../utils'

function initUser(){
  var ret = null
  if (localStorage.getItem('me') != null ) {
    window._me = ret = JSON.parse(localStorage.getItem('me'))
  }
  return ret
}

const state = {
  access_token: localStorage.getItem('access_token') || null,
  refresh_token: localStorage.getItem('refresh_token') || null,
  name: 'LARAVEL-RENTAL',
  me: initUser(),
}

const mutations = {
  LOGOUT: state => {
    state.accessToken = null
    state.refresh_token = null
    state.me = null
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('me')
  },
  TOGGLE_SIDEBAR: state => {
  },
  UPDATE_ACCESS_TOKEN: (state, tk) => (state.access_token = tk),
  UPDATE_REFRESH_TOKEN: (state, tk) => (state.refresh_token = tk),
  UPDATE_ME: (state: any, me: any) => (state.me = me)
}

const actions = {
  logout(context) {
    return new Promise((resolve, reject) => {
      axios
          .delete(url('/api/logout'))
          .then(response => {
            resolve(response)
          })
          .catch(err => {
            reject(err)
          })
    })
  },
  me(context) {
    return axios.get(url('/api/me')).then(response => {
      var me = response.data
      localStorage.setItem('me', JSON.stringify(me))
      context.commit('UPDATE_ME', me)
    })
  },
  retrieveToken(context, credentials) {
    return new Promise((resolve, reject) => {
      axios
          .post(url('/api/login'), credentials)
          .then(response => {
            const accessToken = response.data.access_token
            const refreshToekn = response.data.refresh_token
            localStorage.setItem('access_token', accessToken)
            localStorage.setItem('refresh_token', refreshToekn)
            context.commit('UPDATE_ACCESS_TOKEN', accessToken)
            context.commit('UPDATE_REFRESH_TOKEN', refreshToekn)
            resolve(response)
          })
          .catch(err => {
            Log.error(err)
            reject(err)
          })
    })
  },
}

const getters = {
  isLogined: state => state.access_token !== null
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
